import 'ol/ol.css';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import XYZ from 'ol/source/XYZ';
import Icon from 'ol/style/Icon';
import Style from 'ol/style/Style';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { Point } from 'ol/geom';
import Feature from 'ol/Feature';

import { now, FrameLoopMachine } from '../utils/FrameLoopMachine.js'

export const initialize = (id) => {

    // 场景
    const view = new View({ projection: "EPSG:3857", center: [0.0, 0.0], zoom: 10, });
    const map = new Map({ target: id, view: view, layers: [], });
    const vectorSource = new VectorSource();
    const vectorLayer = new VectorLayer({ source: vectorSource });
    map.addLayer(vectorLayer);

    // 生成小车
    const feature = new Feature({ geometry: new Point([0.0, 0.0]) });
    const iconStyle = new Style({ image: new Icon({ src: "/aht.png", anchor: [0.5, 0.5] }) });
    feature.setStyle(iconStyle);
    vectorSource.addFeature(feature);

    const moveFeature = () => {
        const x = feature.getGeometry().flatCoordinates[0];
        const y = feature.getGeometry().flatCoordinates[1];
        const deltaY = 400;
        const updatedLocation = [x, y + deltaY];

        // 经纬度转像素坐标取整, 反向映射经纬度坐标, 再更新经纬度
        let enablePixelround = false;
        const pixelCoord = map.getPixelFromCoordinate(updatedLocation);
        if (pixelCoord) {
            const integerPixelCoord = [Math.round(pixelCoord[0]), Math.round(pixelCoord[1])];
            const geographicCoord = map.getCoordinateFromPixel(integerPixelCoord);
            feature.getGeometry().setCoordinates(geographicCoord);
            enablePixelround = true;
        }

        // 如果API不可用, 直接更新经纬度
        if (!enablePixelround) {
            feature.getGeometry().setCoordinates(updatedLocation);
        }
    }

    setInterval(() => { moveFeature(); }, 100);

};